package com.cszy.yydqbfq.ui.fragment

import android.app.Activity.RESULT_OK
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.cszy.yydqbfq.R
import com.cszy.yydqbfq.databinding.FragmentSingerListBinding
import com.cszy.yydqbfq.adapter.GeDanListAdapter
import com.cszy.yydqbfq.base.BaseVMFragment
import com.cszy.yydqbfq.bean.AudioItemBean
import com.cszy.yydqbfq.dialog.BottomCreateSongPop
import com.cszy.yydqbfq.ext.launch
import com.cszy.yydqbfq.ext.toast
import com.cszy.yydqbfq.listener.OnCreateSongListener
import com.cszy.yydqbfq.ui.activity.CreatSongListActivity
import com.cszy.yydqbfq.ui.activity.GeDanListActivity
import com.cszy.yydqbfq.ui.activity.MusicListActivity
import com.cszy.yydqbfq.utils.SpUtils
import com.cszy.yydqbfq.viewmodel.SongListViewModel
import com.hjq.permissions.XXPermissions
import com.hlyj.http.ad.NewGroMoreFeedAdManager
import com.hlyj.http.base.tool.lib_hlyj_base.utils.BaseAppConstans
import com.hnyyac.ad.mds.IAdView
import com.hnyyac.ad.mds.IAdViewListener
import com.hnyyac.ad.mds.manager.AdManager
import com.hnyyac.ad.mds.manager.AdManager.AdLoadListener
import com.hnyyac.ad.mds.utils.BaseAdConstants
import kotlinx.coroutines.launch
import org.litepal.LitePal


class SingerListFragment : BaseVMFragment<SongListViewModel, FragmentSingerListBinding>(),IAdViewListener,OnCreateSongListener {

    private lateinit var madapter: GeDanListAdapter
    private var selectMode:Boolean=false    //是否显示选择删除歌单
    private var newGromoreFeedAd : NewGroMoreFeedAdManager? =null
    var type_proces: String? = null //功能入口类型
    var app_process: String? = "0" //整个应用流程
    // 方案2：修正 lazy 初始化
    // 在类体中声明
    private lateinit var editGeDanPop : BottomCreateSongPop;



    private fun initEditGeDanPop(name: String, cover: String, songlistbeanId: Long) : BottomCreateSongPop {
         return BottomCreateSongPop(
            requireActivity(),
            this,
            name,
            cover,
              songlistbeanId
        )
    }

    // 在类顶部定义（例如在 Activity 或 Fragment 中）
    private val createSongListLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == RESULT_OK) {
            AdManager.loadChapin_nocache(
                requireActivity(),
                55,
                this,
                object : AdLoadListener {
                    override fun onAdLoadFailed(ad: IAdView?) {

                    }
                })
        }
    }
    override fun initView(savedInstanceState: Bundle?) {
        app_process = SpUtils.getInstance().getString(BaseAppConstans.APP_PROCESS)
    }

    override fun initData() {
        newGromoreFeedAd = NewGroMoreFeedAdManager(requireActivity(), BaseAdConstants.FEEDAD_Id, mBinding?.frameLayoutBanner,22)
        newGromoreFeedAd?.loadAd()
        madapter= GeDanListAdapter()
        mBinding.recyGedan.layoutManager= LinearLayoutManager(requireContext())
        mBinding.recyGedan.adapter=madapter

    }

    override fun onResume() {
        super.onResume()
        mViewModel.loadPlaylists()
        //更改adapter中 第一个 isLocal为ture 的item中localCount 参数为本地数据库获取音乐的数量
         if (madapter!=null && madapter.items[0].isLocal){
            val localList = LitePal.findAll(AudioItemBean::class.java)
            madapter.items[0].localCount=localList.size
            madapter.notifyItemChanged(0)
        }
        checkMediaPermission()
    }

    override fun initObserve() {
      mViewModel.playlists.observe(this){
          madapter.submitList(it)
      }
    }


    override fun initListener() {
       mBinding.rvAddList.setOnClickListener {
           //新建歌单
           if (app_process=="0"){
               val intent = Intent(requireActivity(), CreatSongListActivity::class.java)
               createSongListLauncher.launch(intent)
           }else{
               type_proces = "点击创建歌单"
               AdManager.loadVideo_nocache(
                   requireActivity(),
                   54,
                   this@SingerListFragment,
                   object : AdLoadListener {
                       override fun onAdLoadFailed(ad: IAdView?) {
                           val intent = Intent(requireActivity(), CreatSongListActivity::class.java)
                           createSongListLauncher.launch(intent)
                       }
                   })
           }

       }

      //adapter点击item事件
        madapter.setOnItemClickListener { adapter, view, position ->
            val item = adapter.items[position]
            if (selectMode){
                mViewModel.toggleItemSelection(item.id) // 切换选中状态
                adapter.items[position].isSelected=!adapter.items[position].isSelected
                madapter.notifyItemChanged(position)
            }else {
                if (item.isLocal) {//如果是本地音乐
                    if (XXPermissions.isGranted(
                            requireContext(),
                            android.Manifest.permission.READ_MEDIA_AUDIO
                        )
                    ) {
                        var bundle = Bundle()
                        bundle.putString("category", "本地音乐")
                        launch(bundle, MusicListActivity::class.java)

                    } else {
                        request_Permission(
                            requireActivity(),
                            android.Manifest.permission.READ_MEDIA_AUDIO,
                            "音频权限",
                            "应用需要访问取您的存储权限，获取整个设备的音频文件资源用于播放器播放设备音乐"
                        )
                    }
                } else {
                    //点击进入歌单详情
                    var bundle = Bundle()
                    bundle.putString("cover", adapter.getItem(position)?.cover.toString())
                    bundle.putString("name", adapter.getItem(position)?.name.toString())
                    bundle.putLong("id", adapter.getItem(position)?.id!!)
                    launch(bundle, GeDanListActivity::class.java)
                }

            }
       }

        madapter.addOnItemChildClickListener(R.id.iv_edit) { adapter, view, position ->
            val item = adapter.items[position]
            if (item.isLocal) {
                toast("本地音乐不支持编辑歌单信息")
            } else {
                //点击编辑歌单
                editGeDanPop = initEditGeDanPop(adapter.getItem(position)?.name.toString(), adapter.getItem(position)?.cover.toString(), adapter.getItem(position)?.id!!)
                editGeDanPop.show(view, position)
            }
        }

       //移出歌单点击事件
        mBinding.rvBottomDelete.setOnClickListener {
            if (mViewModel.selectedItems.isNotEmpty()) {
              mViewModel.deleteSelectedPlaylists() // 执行删除
            } else {
               toast("请先选择要删除的歌单")
            }
        }


//        mBinding.rvImportLocal.setOnClickListener {
//            showMediaPermissionDialog()
//        }
    }


    private fun checkMediaPermission() {
        if (XXPermissions.isGranted(
                requireContext(),
                android.Manifest.permission.READ_MEDIA_AUDIO
            )
        ) {
            loadAudioList()
        }
    }


    override fun loadAudioList() {
        showLoading("正在获取本地音乐")
        lifecycleScope.launch { // 使用 lifecycleScope 确保协程与 Activity 生命周期绑定
            try {
                // 调用 suspend 函数获取数据
                val audioList = mViewModel.getAudioInfoListSync()
                dismissLoading()
                // 更新 UI（）
//                mBinding.rvImportLocal.visibility=View.GONE
//                mBinding.rvGoLocal.visibility=View.VISIBLE
//                mBinding.tvLocalAudioNum.text=audioList.size.toString()+"首"

            } catch (e: Exception) {
                // 处理错误（例如 Toast 提示）
                dismissLoading()
                toast("加载音频列表失败: ${e.message}")
            }
        }
    }

    override fun onTrigger(adView: IAdView) {

    }

    override fun onAdShow(adView: IAdView) {

    }

    override fun onAdClick(adView: IAdView) {

    }

    override fun onAdClose(adView: IAdView) {
        when(type_proces){
            "点击创建歌单"->{
                val intent = Intent(requireActivity(), CreatSongListActivity::class.java)
                createSongListLauncher.launch(intent)
            }
        }
    }

    override fun onError(msg: String) {

    }

    override fun onLoadError(adView: IAdView) {

    }

    override fun onSuccess(adView: IAdView) {

    }

    override fun onLoad(adView: IAdView) {

    }

    override fun onSkipped() {

    }

    override fun onNoAd() {

    }

    override fun onTimeOut() {

    }


    val getContent = registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? ->
        uri?.let {
            // 将选中的图片传递给 BottomCreateSongPop
            editGeDanPop?.setCoverUri(it)
        }
    }

    override fun onImageSelected() {
        getContent.launch("image/*")
    }


    override fun onEditSuccess(playlistName: String, coverUri: String?, songlistbeanId: Long?) {
        toast("修改成功")
        mViewModel.updatedPlaylist(songlistbeanId!!, playlistName, coverUri ?: "")
    }

    override fun onDeleteGedan(songlistbeanId: Long?) {
        mViewModel.deletePlaylist(songlistbeanId!!)
    }

}